package com.ccl.iot.dialogs;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnKeyListener;
import android.os.SystemClock;
import android.util.Log;
import android.view.KeyEvent;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.ccl.iot.publics.Messager;
import com.ccl.iot.privates.RomInfoBean;
import com.ccl.iot.publics.ThreadPoolUtils;
import com.ccl.iot.publics.UIUtils;
import com.ccl.iot.updater.HttpHelper;
import com.ccl.iot.updater.HttpHelper.HttpDownloadListener;
import com.ccl.iot.IOTCallback.UpgradeProgressCallback;
import com.ccl.iot.IOTNetAPI;
import com.ccl.iot.R;
import com.ccl.iot.device.IOTDevice;
import com.ccl.iot.object.IOTDeviceInfoEx;

import java.io.File;

/**
 * 更新设备固件时的dialog,现已被替换(不用dialog)
 */
public class UpgradeDeviceRomDialog {

	private AlertDialog mDialog;
	private RomInfoBean mRomInfo;
	private String[] mUpgradeInfos;
	private ProgressBar mPb;
	private TextView mDes;
	private TextView mProgress;
	private String mUrl;
	private Context mContext;
	private IOTNetAPI mApi;
	private IOTDeviceInfoEx mDevInfo;
	private IOTDevice mDev;
	private boolean mUpgradeOne;

	public UpgradeDeviceRomDialog(Context context, RomInfoBean romInfo, String callBackInfo, IOTDevice dev, boolean upgradeOne) {
		mContext = context;
		mApi = IOTNetAPI.GetInstance();
		mRomInfo = romInfo;
		mDev = dev;
		mUpgradeOne = upgradeOne;
		mDevInfo = dev.getDeviceInfo();
		mUpgradeInfos = callBackInfo.split("#");
		mUrl = "http://iot.cclcp.com:5499/Downloads/Firmware/CCL" + getModel(mDevInfo.iModel) + "/firmware.bin";
		builderDialog(context);
		initView();
		initData();
	}

	private void builderDialog(Context context) {
		AlertDialog.Builder builder = new AlertDialog.Builder(context, AlertDialog.THEME_DEVICE_DEFAULT_LIGHT);
		builder.setCancelable(false);
		mDialog = builder.show();
		mDialog.setContentView(R.layout.dialog_upgrade_rom);
	}

	private void initView() {
		if (mDialog != null) {
			mPb = (ProgressBar) mDialog.findViewById(R.id.dialog_upgrade_pb);
			mDes = (TextView) mDialog.findViewById(R.id.dialog_upgrade_tv_des);
//			mProgress = (TextView) mDialog.findViewById(R.id.dialog_upgrade_rv_progress);
		}
	}

	private void initData() {
		if (mPb != null) {
			// mPb.setMax(max);
			mPb.setProgress(0);
		}

		if (mDes != null) {
			mDes.setText(R.string.DownLoading);
		}
		if (mProgress != null) {
			mProgress.setText("0%");
		}

		mDialog.setOnKeyListener(new OnKeyListener() {

			@Override
			public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
				if (keyCode == KeyEvent.KEYCODE_BACK) {
					mDialog.dismiss();
				}
				return true;
			}
		});

		ThreadPoolUtils.getInstance().addTask(new Runnable() {

			@Override
			public void run() {
				HttpHelper.GetHttpRequestFile(mUrl, GetDefaultDownloadRom(), new HttpDownloadListener() {

					@Override
					public void onDownloadProgress(final int aSize, int aPos) {
						mPb.setMax(aSize);
						mPb.setProgress(aPos);
						UIUtils.postTaskSafely(new Runnable() {

							@Override
							public void run() {
								mProgress.setText((long) mPb.getProgress() * 100 / (long) aSize + "%");
							}
						});
					}
				});
				
				UIUtils.postTaskSafely(new Runnable() {

					@Override
					public void run() {
						mDes.setText(R.string.DownLoadSuccess);
					}
				});
				SystemClock.sleep(1000);
				UIUtils.postTaskSafely(new Runnable() {

					@Override
					public void run() {
						mDes.setText(R.string.Upgrading);
					}
				});

				if(mUpgradeOne){
					mApi.upgradeOne(GetDefaultDownloadRom(), (short) mDevInfo.iType, (short) mDevInfo.iModel, mRomInfo.Code+10, Integer.parseInt(mUpgradeInfos[0]), Short.parseShort(mUpgradeInfos[1]), callback);
				}else{
					mApi.upgradeAll(GetDefaultDownloadRom(), (short) mDevInfo.iType, (short) mDevInfo.iModel, mRomInfo.Code+10, callback);
				}
			}
		});

	}

	public String getModel(int model) {
		if (model == 55132) {
			return "55d1";
		} else {
			return model+"";
		}
	}

	public String GetDefaultDownloadRom() {
		if (mContext != null && mRomInfo != null) {
			return mContext.getExternalCacheDir().getAbsolutePath() + "/firmware" + mRomInfo.Code + ".bin";
		}

		return null;
	}
	
	private UpgradeProgressCallback callback = new UpgradeProgressCallback() {

		@Override
		public void onUpgradeProgressCallback(long aDevID, final int aTotal, final int aProgress) {
			
			mPb.setMax(aTotal);
			mPb.setProgress(aProgress);
			Log.d("upgrade", "aDevID:" + aDevID);
			Log.d("upgrade", "aTotal:" + aTotal);
			Log.d("upgrade", "aProgress:" + aProgress);
			
				UIUtils.postTaskSafely(new Runnable() {

					@Override
					public void run() {
						mProgress.setText((long) mPb.getProgress() * 100 / (long) aTotal + "%");
					}
				});
			
			if (aProgress >= aTotal) {
				if(mListener != null){
					mListener.onSuccess();
				}
				UIUtils.postTaskSafely(new Runnable() {

					@Override
					public void run() {
						mDes.setText(UIUtils.getContext().getResources().getText(R.string.UpgradeSuccess) + mDev.getName());
						
						Messager.Show(R.string.UpgradeSuccess, 0);
					}
				});
				Log.d("upgrade", "升级成功");
				Log.d("upgrade", "aTotal:" + aTotal);
				Log.d("upgrade", "aProgress:" + aProgress);
				File file = new File(GetDefaultDownloadRom());
				if (file.exists()) {
					file.delete();
					file = null;
				}
				mDialog.dismiss();
			}else{
				if(mListener != null){
					mListener.onFail();
				}
			}
		}

	};
	
	private OnUpgradeDone mListener;
	public void setOnUpgradeDone(OnUpgradeDone listener){
		mListener = listener;
	}
	public interface OnUpgradeDone{
		public void onSuccess();
		public void onFail();
	}

}
